package com.zjitc.service.imp;

import com.zjitc.dao.CartDao;
import com.zjitc.dao.ProductDao;
import com.zjitc.model.Cart;
import com.zjitc.model.CartItem;
import com.zjitc.model.Product;
import com.zjitc.service.CartService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/26 16:36
 * @description:
 */
@Service
public class CartServiceImp implements CartService {

  @Autowired
  private CartDao cartDao;

  @Autowired
  private ProductDao productDao;

  @Override
  public void add(String uid, String pid, Integer count) {
    Cart p = cartDao.findPid(pid);
    if (p!=null) {
      count=count+p.getCount();
      cartDao.updateCount(String.valueOf(count),pid);
    } else {
      cartDao.add(uid, pid, String.valueOf(count));
    }
  }

  @Override
  public List<CartItem> findAll(String uid) {
    List<Cart> checkCartIsNull = cartDao.checkCartIsNull(uid);
    List<CartItem> cartItems = new ArrayList<CartItem>();
    for (Cart cart : checkCartIsNull) {
      Product p = productDao.findByPid(cart.getPid());

      cartItems.add(new CartItem(cart.getCount(), p.getShop_price() * cart.getCount(), p));
    }
    return cartItems;
  }

  @Override
  public void removeProduct(String pid) {
    cartDao.removeProduct(pid);
  }

  @Override
  public void clearCart(String uid) {
    cartDao.clearCart(uid);
  }

  @Override
  public Cart findByPid(String pid) {
    return cartDao.findPid(pid);
  }

}